<?php

/*Af*/

namespace App\Tools;

use App\Tools\Curl;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Af {
	private $config;

	public $tableName = "af_event_log";

	public function __construct() {
		$this->config = [
			'apiHost' => 'https://api2.appsflyer.com/inappevent/'
		];
	}

	/**
	 * @desc  上报数据
	 * @return string
	 * */
	public function reportEvent($appsflysid = "", $appId = '', $eventData = [], $aExt=[]) {
		if(empty($appsflysid))return false;
		$headers = array();
		$headers[] = "Content-Type:application/json";
		$headers[] = "AUTHENTICATION:irmBDPSXfjApoKo2mdpsFA";
		$params = [
			'appsflyer_id' => $appsflysid, 'eventName' => $eventData['eventName'],
			'eventValue' => $eventData['eventValue']
		];

		$curl = new Curl();
		$result = $curl->curl_request($this->config['apiHost'].$appId, $params, 'json', 'POST', $headers);

		Log::info('appsflyLog', [
			'params' => $params, 'eventData' => $eventData, 'result' => $result, 'appsflysid' => $appsflysid
		]);

		$this->addEventLog($appsflysid, $eventData['eventName'], (isset($eventData['eventValue']) ? $eventData['eventValue'] : ''), $result, $aExt);

		return true;
	}

	//支付事件
	public function payEvent($af_id, $appid, $price, $aExt=[]) {
		$afJson = json_encode(['af_revenue' => $price / 100, 'af_currency' => 'USD']);
		$this->reportEvent($af_id, $appid, ['eventName' => "pay_event", "eventValue" => $afJson], $aExt);
	}

	//订阅
	public function subscribeEvent($af_id, $appid, $aExt=[]) {
		$this->reportEvent($af_id, $appid, ['eventName' => "subscribe_event", "eventValue" => ""], $aExt);
	}


	/**
	 * @param array $aData
	 * @return bool
	 */
	public function addData($aData) {
		return DB::table($this->tableName)->insert($aData);
	}

	/**
	 * @param string $sAFID
	 * @param string $sEvent
	 * @param string $sEventValue
	 * @param string $sResCode
	 * @return bool
	 */
	public function addEventLog($sAFID, $sEvent, $sEventValue, $sResCode, $aExt=[]) {
		if(empty($sAFID))return false;
		$aData = [];
		$aData['af_id'] = $sAFID;
		$aData['event'] = $sEvent;
		$aData['event_value'] = empty($sEventValue) ? '[]' : (is_array($sEventValue) ? json_encode($sEventValue) : $sEventValue);
		$aData['result_code'] = $sResCode;
		$aData['created_time'] = date('Y-m-d H:i:s');

		if(!empty($aExt)){
			$aData['ext'] = json_encode($aExt);
		}
		return $this->addData($aData);
	}
}
